package io.gitee.twoke.generator.engine.impl.generate.processor;


import io.gitee.twoke.generator.engine.GenerateService;
import io.gitee.twoke.generator.engine.TemplateService;
import io.gitee.twoke.generator.engine.impl.generate.DataTable;
import io.gitee.twoke.generator.engine.impl.template.TemplateFile;
import cn.hutool.core.collection.CollectionUtil;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public abstract class AbstractGenerateProcessorExecutor implements GenerateExecutor {

    @Override
    public void execute(String id) {
        GenerateProcessContext context = createContext(id);
        invokeProcess(context);
    }

    protected GenerateProcessContext createContext(String id) {
//      数据表
        DataTable dataTable = getGenerateService().createDataTableQuery().id(id).singleResult();
        if (dataTable == null) {
            throw new IllegalArgumentException("table id " + id + " not exist");
        }
        List<String> groupIds = Arrays.asList(dataTable.getTemplateGroupIds().split(","));
//      模板
        List<TemplateFile> list = CollectionUtil.isEmpty(groupIds) ? new ArrayList<>() : getTemplateService().createTemplateFileQuery()
                .groupIds(groupIds).list();

        return new GenerateProcessContext() {
                @Override
                public List<TemplateFile> getTemplateFiles() {
                    return list;
                }

                @Override
                public DataTable getTableConfig() {
                    return dataTable;
                }
        };
    }
    protected abstract void invokeProcess(GenerateProcessContext context);


    protected abstract TemplateService getTemplateService();
    protected abstract GenerateService getGenerateService();
}
